package com.stdz.counter.core.thread;

import com.stdz.counter.core.cache.MeterInfoCache;
import com.stdz.counter.dao.MeterInfoDao;
import com.stdz.counter.utils.MeterClearHelper;
import com.stdz.counter.utils.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

public class ClearCheckThread implements Runnable {

    private static transient Logger logger = LoggerFactory.getLogger(ClearCheckThread.class);

    @Resource
    private MeterInfoDao meterInfoDao;

    public ClearCheckThread() {
        ResourceUtil.autowired(this);
    }

    public void run() {
        while (true) {
            long checkStartTime = System.currentTimeMillis();
            this.checkComPorts();
            long checkEndTime = System.currentTimeMillis();
            long span = checkEndTime - checkStartTime;
            if (span < 2000L) {
                try {
                    Thread.sleep(2000 - span);
                } catch (InterruptedException e) {
                    logger.error("thread InterruptedException:", e);
                }
            }

        }

    }

    private void checkComPorts() {
        List<String> comPorts = MeterInfoCache.getInstance().getComPorts();
        if (comPorts != null && comPorts.size() > 0) {
            for (String comPort : comPorts) {
                try {
                    MeterClearHelper.getInstance().checkClearTask(comPort);
                } catch (Throwable t) {
                    logger.error("check clear task exception:", t);
                }

            }
        }
    }

}
